package com.xunshangwang.pinhaohuo.ui.fragments;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.RequestParams;
import com.xunshangwang.pinhaohuo.R;
import com.xunshangwang.pinhaohuo.adapters.OrderAdapter;
import com.xunshangwang.pinhaohuo.decorations.DividerItemDecoration;
import com.xunshangwang.pinhaohuo.decorations.OffsetItemDecoration;
import com.xunshangwang.pinhaohuo.entity.Order;
import com.xunshangwang.pinhaohuo.http.HttpTool;
import com.xunshangwang.pinhaohuo.http.JsonHttpHandler;
import com.xunshangwang.pinhaohuo.ui.activities.GroupDetailActivity;
import com.xunshangwang.pinhaohuo.ui.activities.OrderDetailActivity;
import com.xunshangwang.pinhaohuo.ui.dialogs.LogisticsDialog;
import com.xunshangwang.pinhaohuo.widgets.LMSizeRecyclerView;
import com.xunshangwang.pinhaohuo.widgets.LoadLayout;
import com.xunshangwang.pinhaohuo.widgets.RefreshLayout;

import org.json.JSONObject;

import java.util.List;

import cz.msebera.android.httpclient.Header;
import tool.library.ToastTool;
import tool.library.adapter.BaseRecyclerAdapter;
import tool.library.widget.LoadRecyclerView;

/**
 * Created by xzp on 16/3/10.
 */
public class OrderListFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener,LoadRecyclerView.OnLoadListener,
        OrderAdapter.OnFunctionClickListener,BaseRecyclerAdapter.OnItemClickListener{
    private LoadLayout mLoad;
    private RefreshLayout mRefresh;
    private LMSizeRecyclerView mRecycler;
    private int mOrderStatus;
    private OrderAdapter mAdapter;
    public static final OrderListFragment newInstance(int status){
        OrderListFragment fragment=new OrderListFragment();
        Bundle bundle=new Bundle();
        bundle.putInt("status",status);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(getArguments()!=null){
            mOrderStatus=getArguments().getInt("status",-1);
        }
    }



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mLoad= (LoadLayout) inflater.inflate(R.layout.fragment_order_list, container, false);
        mRefresh= (RefreshLayout) mLoad.findViewById(R.id.refresh_layout);
        mRecycler= (LMSizeRecyclerView) mLoad.findViewById(R.id.order_list);
        mRecycler.addItemDecoration(new OffsetItemDecoration(inflater.getContext(),R.dimen.order_list_item_offset));
        mRecycler.setLayoutManager(new LinearLayoutManager(inflater.getContext()));
        mRefresh.setOnRefreshListener(this);
        mRecycler.setOnLoadListener(this);
        mAdapter=new OrderAdapter(inflater.getContext());
        mAdapter.setOnFunctionClickListener(this);
        mAdapter.setOnItemClickListener(this);
        mRecycler.setAdapter(mAdapter);
        return mLoad;
    }

    @Override
    public void onCancel(final int position) {
        if(mRefresh.isRefreshing())
            return;
        AlertDialog.Builder builder=new AlertDialog.Builder(getContext());
        builder.setMessage("你确定要取消该订单吗?");
        builder.setPositiveButton("立即取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                JsonHttpHandler<Void> handler = new JsonHttpHandler<Void>() {
                    @Override
                    public Void parseData(JSONObject object) throws Throwable {
                        return null;
                    }

                    @Override
                    public void onStart() {
                        super.onStart();
                        mLoad.startLoad();
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        mLoad.finishLoad();
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Void response) {
                        ToastTool.showToast("取消订单成功");
                        mAdapter.getList().remove(position);
                        mAdapter.notifyItemRemoved(position);
                    }
                };
                handler.setTag(getView());
                StringBuilder stringBuilder = new StringBuilder("?g=Api&m=Weuser&a=cancelOrder");
                stringBuilder.append("&token=" + getMainApplication().getToken());
                stringBuilder.append("&order_id=" + mAdapter.getList().get(position).getOrder_id());
                HttpTool.get(getContext(), stringBuilder.toString(), handler);
            }
        });
        builder.setNegativeButton("取消",null);
        builder.show();
    }

    @Override
    public void onLogistics(int position) {
        LogisticsDialog dialog=LogisticsDialog.newDialog(mAdapter.getList().get(position).getOrder_id());
        dialog.show(getChildFragmentManager(),"logistics");
    }

    @Override
    public void onConfirm(final int position) {
        if(mRefresh.isRefreshing())
            return;
        JsonHttpHandler<Void> httpHandler=new JsonHttpHandler<Void>() {
            @Override
            public void onStart() {
                super.onStart();
                mLoad.startLoad();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mLoad.finishLoad();
            }

            @Override
            public Void parseData(JSONObject object) throws Throwable {
                return null;
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Void response) {
                mAdapter.notifyItemRemoved(position);
            }
        };
        httpHandler.setTag(getView());
        StringBuilder builder=new StringBuilder("?g=Api&m=Weuser&a=receivedOrder");
        builder.append("&token="+getMainApplication().getToken());
        builder.append("&order_id="+mAdapter.getList().get(position).getOrder_id());
        HttpTool.get(getContext(),builder.toString(),httpHandler);
    }
    //    @Override
//    public void onGroupDetail(int position) {
//        Intent intent=new Intent(getContext(), GroupDetailActivity.class);
//        intent.putExtra("id",mAdapter.getList().get(position).getGroup_order_id());
//        startActivity(intent);
//    }

    @Override
    public void onItemClick(BaseRecyclerAdapter adapter, View item, int position) {
        Intent intent=new Intent(getContext(), OrderDetailActivity.class);
        intent.putExtra("id",mAdapter.getList().get(position).getOrder_id());
        startActivity(intent);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if(getUserVisibleHint()==true){
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mRefresh.setRefreshing(true);
                    onRefresh();
                }
            },150);
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser && mRefresh!=null && !mRefresh.isRefreshing()){
            mRefresh.setRefreshing(true);
            onRefresh();
        }
    }

    @Override
    public void onLoad(LoadRecyclerView recyclerView) {
        loadList();
    }

    @Override
    public void onRefresh() {
        refreshList();
    }
    private void refreshList(){
        StringBuilder builder=new StringBuilder("?g=Api&m=Weuser&a=order");
        builder.append("&token="+getMainApplication().getToken());
        builder.append("&offset=0");
        builder.append("&size="+LMSizeRecyclerView.SIZE);
        if(mOrderStatus>=0){
            builder.append("&order_status="+mOrderStatus);
        }
        JsonHttpHandler<List<Order>> handler=new JsonHttpHandler<List<Order>>() {
            @Override
            public void onFinish() {
                super.onFinish();
                mRefresh.setRefreshing(false);
            }

            @Override
            public List<Order> parseData(JSONObject object) throws Throwable {
                return JSON.parseArray(object.getString("order_list"),Order.class);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, List<Order> response) {
                mAdapter.setList(response);
                mRecycler.loadFinish(response);
            }
        };
        handler.setTag(getView());
        HttpTool.get(getContext(), builder.toString(), handler);
    }
    private void loadList(){
        StringBuilder builder=new StringBuilder("?g=Api&m=Weuser&a=order");
        builder.append("&token="+getMainApplication().getToken());
        builder.append("&offset="+mAdapter.getListSize());
        builder.append("&size="+LMSizeRecyclerView.SIZE);
        if(mOrderStatus>=0){
            builder.append("&order_status="+mOrderStatus);
        }
        JsonHttpHandler<List<Order>> handler=new JsonHttpHandler<List<Order>>() {

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, List<Order> errorResponse) {
                super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
                mRecycler.loadFinish();
            }

            @Override
            public List<Order> parseData(JSONObject object) throws Throwable {
                return JSON.parseArray(object.getString("order_list"),Order.class);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, List<Order> response) {
                mAdapter.addAll(response);
                mRecycler.loadFinish(response);
            }
        };
        handler.setTag(getView());
        HttpTool.get(getContext(), builder.toString(), handler);
    }
}
